import {
	BLUE_STATE
} from './blueState.js'
import {
	ConnectController
} from './controller.js'
import DataChannel from './BTSerial.js';



export const Blue = {
	/**
	 * 蓝牙连接状态：200-> 已连接；-1 ->未连接
	 */
	connectState: -1,
	deviceList: [],
	bleConnectDeviceID: null,
	writeCharacteristicId: null,
	serviceId: null,
	notifyCharacteristic: null,
	dataChannel: null,
	/**
	 * 扫描蓝牙设备
	 * @param onlyBind 是否单独绑定操作，默认false
	 * @param module 设备模块，区分设备
	 */
	start() {
		uni.openBluetoothAdapter({
			success: () => {
				this.startBluetoothDevicesDiscovery()
			},
			fail: (res) => {
				console.error('打开蓝牙适配器失败：', res)
				if (res.errCode === 10001) {
					if (res.state === 3) {
						ConnectController.connectStateListen(BLUE_STATE.NOBLUETOOTHPERMISSION)
					} else {
						ConnectController.connectStateListen(BLUE_STATE.UNAVAILABLE)
					}

				}
				// Android 系统特有，系统版本低于 4.3 不支持 BLE
				if (res.errCode === 10009) {
					ConnectController.connectStateListen(BLUE_STATE.VERSIONLOW)
				}
				if (res.errCode === 10008) {
					ConnectController.connectStateListen(BLUE_STATE.SYSTEMERROR)
				}
			},
			complete: () => {
				uni.offBluetoothAdapterStateChange()
				uni.onBluetoothAdapterStateChange((res) => {
					if (this._discoveryStarted) return
					if (res.available) {
						console.log('蓝牙适配器可用', res)
						this._discoveryStarted = res.discovering
						ConnectController.connectStateListen(BLUE_STATE.SCANING)
						this.startBluetoothDevicesDiscovery()
					} else {
						// 蓝牙模块未开启
						console.log('蓝牙模块未开启')
						ConnectController.connectStateListen(BLUE_STATE.UNAVAILABLE)
					}
				})
			}
		})

	},
	initDataChannel() {
		this.dataChannel = new DataChannel(this.sendDataViaBluetooth)
		uni.onBLECharacteristicValueChange((res) => {
			//console.log("onBLECharacteristicValueChange:" + res);
			//console.log(res.value);
			this.dataChannel.onRecvData(res.value, (percent, offset, status) => {
				console.log(`接收进度: ${percent}% 状态: ${status}`);
			});
		});
	},
	/**
	 * 关闭蓝牙、初始化BLE状态
	 */
	closeBlue() {
		console.log('关闭蓝牙');
		if (this.bleConnectDeviceID) {
			uni.closeBLEConnection({
				deviceId: this.bleConnectDeviceID,
			})
		}
		this.bleConnectDeviceID = null
		this.connectState = -1
		this.notifyCharacteristicId = null
		this.writeCharacteristicId = null
		this.serviceId = null
		this.dataChannel = null
		this._discoveryStarted = false
		uni.closeBluetoothAdapter({})
		uni.offBluetoothAdapterStateChange()
		uni.offBLEConnectionStateChange()
		uni.stopBluetoothDevicesDiscovery({})
	},
	/**
	 * 断开蓝牙
	 */
	closeBLEConnection() {
		console.log('断开蓝牙');
		uni.closeBLEConnection({
			deviceId: this.bleConnectDeviceID,
			success: () => {
				this.bleConnectDeviceID = null
				this.notifyCharacteristicId = null
				this.writeCharacteristicId = null
				this.serviceId = null
				this.dataChannel = null
				this.connectState = -1
				// uni.showToast({
				// 	icon: 'none',
				// 	title: '蓝牙已断开连接'
				// })
			},
			fail: (res) => {
				console.log('断开蓝牙失败==>', JSON.stringify(res));
			}
		})
	},
	stopBLE() {
		uni.stopBluetoothDevicesDiscovery({
			success(res) {
				console.log('关闭搜索蓝牙');
			},
			fail: (res) => {
				console.log('关闭搜索蓝牙失败==>', JSON.stringify(res));
			}
		})
	},

	startBluetoothDevicesDiscovery() {
		if (this._discoveryStarted) {
			return
		}
		this._discoveryStarted = true
		uni.startBluetoothDevicesDiscovery({
			allowDuplicatesKey: false,
			interval: 1000,
			success: () => {
				this.onBluetoothDeviceFound()
				console.log('扫描中.....')
			},
			fail: (res) => {
				console.error('搜索外围设备失败--', res)
				const {
					locationAuthorized
				} = uni.getSystemInfoSync()
				if (res.errCode === -1 && (res.errno === 1509008 || res.errno === 1509009) || !
					locationAuthorized) {
					this.closeBlue()
					ConnectController.connectStateListen(BLUE_STATE.NOLOCATIONPERMISSION)
				}
			}
		})
	},

	onBluetoothDeviceFound() {
		ConnectController.connectStateListen(BLUE_STATE.SCANING)
		const prefix = "YM_";
		uni.onBluetoothDeviceFound((res) => {
			res.devices.forEach(device => {
				const deviceName = device.name || device.localName
				if (!deviceName) return
				if (device.name && device.name.startsWith(prefix)) {
					const index = this.deviceList.findIndex(item => item.name === device.name)
					if (index < 0) {
						this.deviceList.push(device)
					}
				}
				ConnectController.devicesListen(device)
			})
		})
	},

	createBLEConnection(deviceId, name) {
		if (this.bleConnectDeviceID == null) {
			this.bleConnectDeviceID = deviceId
			console.log('连接设备==>', this.bleConnectDeviceID)
			uni.showLoading({
				title: '连接中...',
				mask: true
			});
			uni.createBLEConnection({
				deviceId: deviceId,
				success: () => {
					this.connectState = 200

					ConnectController.connectStateListen({
						...BLUE_STATE.CONNECTSUCCESS,
						deviceId
					})
					this.onBLEConnectionStateChange()
					uni.showToast({
						icon: 'none',
						title: '设备已连接'
					})
					uni.setStorageSync('bluename', name);
					this.getBLEDeviceServices(deviceId);
				},
				fail: (res) => {
					uni.showToast({
						icon: 'none',
						title: '连接设备失败'
					})
					uni.setStorageSync('bluename', "");
					console.log('连接设备失败==>', JSON.stringify(res))
					ConnectController.connectStateListen(BLUE_STATE.CONNECTFAILED)
				},
				complete: () => {
					uni.hideLoading();
				}
			})
		}
	},

	onBLEConnectionStateChange() {
		uni.onBLEConnectionStateChange(res => {
			if (!res.connected) {
				console.log('蓝牙状态改变')
				ConnectController.connectStateListen(BLUE_STATE.DISCONNECT)
				this.connectState = -1
				this.bleConnectDeviceID = null
				this.notifyCharacteristicId = null
				this.writeCharacteristicId = null
				this.serviceId = null
				this.dataChannel = null
				// this.closeBlue()
			}
		})
	},

	// 获取设备服务
	getBLEDeviceServices(deviceId) {
		uni.getBLEDeviceServices({
			deviceId,
			success: (res) => {
				console.log('获取服务列表成功', res.services);
				const services = res.services;
				if (services.length > 0) {
					//遍历service,找到可以写入的特征列表
					for (var serviceItem of services) {
						const serviceId = serviceItem.uuid;
						this.getBLEDeviceCharacteristics(deviceId, serviceId);
					}
				}
			},
			fail: (err) => {
				console.error('获取服务列表失败', err);
			}
		});
	},

	// 获取特征
	getBLEDeviceCharacteristics(deviceId, serviceId) {

		if (serviceId !== "0000AE30-0000-1000-8000-00805F9B34FB") {
			return;
		}

		uni.getBLEDeviceCharacteristics({
			deviceId,
			serviceId,
			success: (res) => {
				console.log('获取特征列表成功 service:', serviceId);
				const characteristics = res.characteristics;

				// 找到支持写入（write）的特征
				const writeCharacteristic = characteristics.find((char) => char.properties.write);
				if (writeCharacteristic) {
					console.log('找到可写入特征:', writeCharacteristic.uuid);
					if (writeCharacteristic.uuid.startsWith("0000AE01")) {
						console.log('==>使用写入特征:', writeCharacteristic.uuid);
						this.writeCharacteristicId = writeCharacteristic.uuid
						this.serviceId = serviceId
						//this.onBLEWriteUUIDFinished();
					}
				}

				if (!this.notifyCharacteristicId) {
					const notifyCharacteristic = characteristics.find((char) => char.properties.notify);
					if (notifyCharacteristic) {
						console.log('找到notify特征:', notifyCharacteristic.uuid);
						if (notifyCharacteristic.uuid.startsWith("0000AE02")) {
							console.log('==>使用notify特征:', notifyCharacteristic.uuid);
							this.notifyCharacteristicId = notifyCharacteristic.uuid
							this.onBLEWriteUUIDFinished();
						}
					}
				}
				console.log('特征列表打印:', this.serviceId, this.writeCharacteristicId, this
					.notifyCharacteristicId)
			},
			fail: (err) => {
				console.error('获取特征列表失败', err);
			}
		});
	},

	onBLEWriteUUIDFinished() {
		console.log('开始监听读取消息:');
		uni.notifyBLECharacteristicValueChanged({
			state: true, // 启用 notify 功能
			deviceId: this.bleConnectDeviceID,
			serviceId: this.serviceId,
			characteristicId: this.notifyCharacteristicId,
			success(res) {
				console.error('启用接受消息成功');
			},
			fail: (err) => {
				console.error('启用接受消息失败', err);
				uni.showToast({
					title: '启用接受消息失败',
					icon: 'none',
				});
			}
		});
	},

	sendDataViaBluetooth(data) {
		const buffer = new Uint8Array(data).buffer;

		// console.log("-->serviceId:", Blue.serviceId,
		// 	"-->deviceId:", Blue.bleConnectDeviceID,
		// 	" -->writeCharacteristicId:", Blue.writeCharacteristicId);
		uni.writeBLECharacteristicValue({
			deviceId: Blue.bleConnectDeviceID,
			serviceId: Blue.serviceId,
			characteristicId: Blue.writeCharacteristicId,
			value: buffer,
			success: (res) => {
				// console.log("蓝牙数据发送成功", res);
			},
			fail: (err) => {
				console.error("蓝牙数据发送失败", err);
			}
		});
	},
	//发送网络图片
	sendNetworkImageBLEMessage(imageUrl) {
		if (!this.bleConnectDeviceID) {
			uni.showToast({
				title: '请先连接蓝牙',
				icon: 'none',
			});
			return;
		}
		this.downloadFile(imageUrl, (downloadRes) => {
			this.readFile(downloadRes.tempFilePath, (buffer) => {
				this.sendBinaryFile(buffer)
			});
		});
	},

	downloadFile(imageUrl, callback) {
		uni.downloadFile({
			url: imageUrl,
			success: (res) => {
				if (callback) {
					callback(res);
				}
			},
			fail: (err) => {
				console.error('读取图片失败', err);
				uni.showToast({
					title: '读取图片失败',
					icon: 'none',
				});
			}
		});
	},

	readFile(path, callback) {
		uni.getFileSystemManager().readFile({
			filePath: path,
			success: (readRes) => {
				uni.showToast({
					title: '读取图片成功，开始发送数据',
					icon: 'none',
				});
				const buffer = readRes.data; // ArrayBuffer 格式
				if (callback) {
					callback(buffer)
				}
			},
			fail: (err) => {
				console.error('读取图片失败', err);
				uni.showToast({
					title: '读取图片失败',
					icon: 'none',
				});
			}
		});
	},

	sendBinaryFile(fileData) {
		if (!this.dataChannel) {
			console.log("dataChannel初始化")
			this.initDataChannel()
		}
		const format = "jpg"; // 假设发送的是jpg格式
		try {
			this.dataChannel.sendBinaryFile(fileData, format, (percent, offset, status) => {
				console.log(`文件发送进度: ${percent}% 已发送: ${offset} 状态: ${status}`);
				// 根据状态处理文件发送的不同阶段
				if (status === "success") {
					uni.hideLoading();
					console.log("文件发送成功");
					uni.showToast({
						title: '图片发送成功',
						icon: 'success',
					});
				} else if (status === "start") {
					uni.showLoading({
						mask: true,
						title: '图片发送中'
					});
					console.log("文件发送开始");
				} else if (status === "sending") {
					//console.log(`文件发送中... ${percent}% 完成`);
					uni.showLoading({
						mask: true,
						title: `图片发送中进度: ${percent}%`
					});
				} else {
					uni.hideLoading();
					console.error("文件发送失败: ", status);
				}
			})
		} catch (error) {
			console.error(error);
		}
	},

	onResetFileTranse() {
		if (!this.bleConnectDeviceID) {
			console.log("未连接蓝牙")
			return;
		}
		if (!this.dataChannel) {
			console.log("未初始化dataChannel")
			return;
		}
		this.dataChannel.resetFileTransfer((percent, offset, status) => {
			console.log(`重置进度: ${percent}% 状态: ${status}`);
		});
	},

	configWifi(ssid, psd) {
		return new Promise((resolve, reject) => {
			console.log("configWifi")
			if (!this.dataChannel) {
				console.log("dataChannel初始化")
				this.initDataChannel()
			}
			// 将 ssid 转换为 UTF-8 编码
			const newSsid = encodeURIComponent(ssid);
			this.dataChannel.SetDevNetwork(newSsid, psd, (percent, offset, data) => {
				console.log(`设置网络返回: ${data}`);
				if (data) {
					resolve(data);
				} else {
					reject(new Error("设置网络出错"));
				}
			});

		});
	},
	getDeviceInfo() {
		return new Promise((resolve, reject) => {
			if (!this.dataChannel) {
				console.log("dataChannel初始化")
				this.initDataChannel()
			}
			this.dataChannel.GetDevInfo((percent, offset, data) => {
				console.log(`获取设备信息返回: ${data}`)
				if (data) {
					resolve(data);
				} else {
					reject(new Error("未能获取设备信息"));
				}
			});
		});
	},

	setCorrectUpdateBLE(state, x1, y1, x2, y2, x3, y3, x4, y4) {
		return new Promise((resolve, reject) => {
			if (!this.dataChannel) {
				console.log("dataChannel初始化")
				this.initDataChannel()
			}
			this.dataChannel.SetCorrectPos(state, x1, y1, x2, y2, x3, y3, x4, y4, (percent, offset,
				data) => {
				console.log(`矫正信息返回: ${data}`)
				if (data) {
					resolve(data);
				} else {
					reject(new Error("未能获取矫正信息"));
				}
			});
		});
	},

	onResetDefaultBLE() {
		return new Promise((resolve, reject) => {
			if (!this.dataChannel) {
				console.log("dataChannel初始化")
				this.initDataChannel()
			}
			this.dataChannel.SetOptions(0, 0, (percent, offset, data) => {
				console.log(`重置参数返回: ${data}`);
			});
		});
	}
}